<?php

namespace app\xs_test\controller\web\goods;

use app\xs_test\facade\service\GoodsCategoryServiceFacade;
use app\xs_test\facade\service\GoodsParamServiceFacade;
use app\xs_test\facade\service\GoodsServiceFacade;
use xsframe\base\AdminBaseController;
use xsframe\util\RandomUtil;
use xsframe\util\StringUtil;
use think\facade\Db;
use think\Image;

class Index extends AdminBaseController
{
    protected $tableName = 'xs_test_shop_goods';

    public function index()
    {
        return $this->main();
    }

    public function main($goodsFrom = "sale")
    {
        $condition = [
            'uniacid' => $this->uniacid
        ];

        if (!empty($this->params['type'])) {
            $condition['type'] = $this->params['type'];
        }

        if (!empty($this->params["attribute"])) {
            if ($this->params["attribute"] == "new") {
                $condition['isnew'] = 1;
            } else {
                if ($this->params["attribute"] == "hot") {
                    $condition['ishot'] = 1;
                } else {
                    if ($this->params["attribute"] == "recommand") {
                        $condition['isrecommand'] = 1;
                    } else {
                        if ($this->params["attribute"] == "sendfree") {
                            $condition['issendfree'] = 1;
                        }
                    }
                }
            }
        }

        $status = 1;

        if ($goodsFrom == "sale") { // 销售中
            $condition['status'] = 1;
            $condition['deleted'] = 0;
        } else {
            if ($goodsFrom == "cycle") { // 已删除
                $status = 0;
                $condition['deleted'] = 1;
            }else{
                if ($goodsFrom == "out") { // 已下架
                    $condition['status'] = 0;
                    $condition['deleted'] = 0;
                }
            }
        }

        if (!empty($this->params["cate"])) {
            $condition[''] = Db::raw(" FIND_IN_SET(" . intval($this->params["cate"]) . ",cates)<>0 ");
        }

        $total = GoodsServiceFacade::getTotal($condition);
        $list = GoodsServiceFacade::getList($condition);

        foreach ($list as $key => &$value) {
            $value["allcates"] = explode(",", $value["cates"]);
            $value["allcates"] = array_unique($value["allcates"]);
        }

        $categorys = GoodsCategoryServiceFacade::getFullCategory(['deleted' => 0, 'uniacid' => $this->uniacid], true);
        $category = array();
        foreach ($categorys as $cate) {
            $category[$cate["id"]] = $cate;
        }


        $result = [
            'status'    => $status,
            'category'  => $category,
            'total'     => $total,
            'list'      => $list,
            'goodsFrom' => $goodsFrom,
        ];
        return $this->template('list', $result);
    }

    public function edit()
    {
        return $this->post();
    }

    public function add()
    {
        return $this->post();
    }

    public function sale()
    {
        return $this->main("sale");
    }

    public function out()
    {
        return $this->main("out");
    }

    public function stock()
    {
        return $this->main("stock");
    }

    public function cycle()
    {
        return $this->main("cycle");
    }

    public function restore()
    {
        $id = ($this->params["id"]);
        if (empty($id)) {
            $id = $this->params["ids"];
        }
        $items = GoodsServiceFacade::getList(['uniacid' => $this->uniacid, 'id' => $id]);
        foreach ($items as $item) {
            GoodsServiceFacade::updateInfo(['deleted' => 0], ['id' => $item['id']]);
        }
        show_json(1, array("url" => referer()));
    }

    public function post()
    {

        $id = ($this->params["id"]);

        if ($this->request->isPost()) {
            $data = array(
                "uniacid"        => $this->uniacid,
                "title"          => trim($this->params["goodsname"]),
                "unit"           => trim($this->params["unit"]),
                "keywords"       => trim($this->params["keywords"]),
                "thumb_first"    => intval($this->params["thumb_first"]),
                "sales"          => intval($this->params["sales"]),
                "isrecommand"    => intval($this->params["isrecommand"]),
                "isnew"          => intval($this->params["isnew"]),
                "ishot"          => intval($this->params["ishot"]),
                "marketprice"    => floatval($this->params["marketprice"]),
                "originalprice"  => trim($this->params["originalprice"]),
                "status"         => intval($this->params["status"]),
                "subtitle"       => trim($this->params["subtitle"]),
                "content"        => htmlspecialchars_decode($this->params["content"]),
                "createtime"     => time(),
                "updatetime"     => time(),
            );

            $pcates = array();
            $ccates = array();
            $tcates = array();
            $cates = array();

            $pcateid = 0;
            $ccateid = 0;
            $tcateid = 0;

            if (is_array($this->params["cates"])) {
                $cates = $this->params["cates"];

                foreach ($cates as $key => $cid) {
                    $c = GoodsCategoryServiceFacade::getInfo(['id' => $cid, 'uniacid' => $this->uniacid], 'level');
                    if ($c["level"] == 1) {
                        $pcates[] = $cid;
                    } else {
                        if ($c["level"] == 2) {
                            $ccates[] = $cid;
                        } else {
                            if ($c["level"] == 3) {
                                $tcates[] = $cid;
                            }
                        }
                    }
                    if ($key == 0) {
                        if ($c["level"] == 1) {
                            $pcateid = $cid;
                        } else {
                            if ($c["level"] == 2) {
                                $crow = GoodsCategoryServiceFacade::getInfo(['id' => $cid, 'uniacid' => $this->uniacid], 'parentid');
                                $pcateid = $crow["parentid"];
                                $ccateid = $cid;
                            } else {
                                if ($c["level"] == 3) {
                                    $tcateid = $cid;
                                    $tcate = GoodsCategoryServiceFacade::getInfo(['id' => $cid, 'uniacid' => $this->uniacid], 'id,parentid');
                                    $ccateid = $tcate["parentid"];
                                    $ccate = GoodsCategoryServiceFacade::getInfo(['id' => $cid, 'uniacid' => $this->uniacid], 'id,parentid');
                                    $pcateid = $ccate["parentid"];
                                }
                            }
                        }
                    }
                }
            }

            $data["pcate"] = $pcateid;
            $data["ccate"] = $ccateid;
            $data["tcate"] = $tcateid;

            $data["cates"] = implode(",", $cates);
            $data["pcates"] = implode(",", $pcates);
            $data["ccates"] = implode(",", $ccates);
            $data["tcates"] = implode(",", $tcates);

            if (is_array($this->params["thumbs"])) {
                $thumbs = $this->params["thumbs"];
                $thumb_url = array();
                foreach ($thumbs as $th) {
                    $thumb_url[] = trim($th);
                }
                $data["thumb_url"] = serialize($thumb_url);
            }

            if (!empty($this->params["thumb"])) {
                $data["thumb"] = $this->params["thumb"];
            }

            $thumbOriginal = [];
            if (!empty($this->params["thumb_original"])) {
                $thumbOriginal['thumb'] = trim($this->params["thumb_original"]);
                $thumbOriginal['size'] = trim($this->params["thumb_original_size"]);
                $thumbOriginal['width'] = trim($this->params["thumb_original_width"]);
                $thumbOriginal['height'] = trim($this->params["thumb_original_height"]);
                $data["thumb_original"] = serialize($thumbOriginal);
            }

            if (empty($id)) {
                $id = GoodsServiceFacade::insertInfo($data);
            } else {
                unset($data['createtime']);
                GoodsServiceFacade::updateInfo($data, ['id' => $id]);
            }

            // 参数
            $param_ids = $this->params['param_id'] ?? [];
            $param_titles = $this->params['param_title'] ?? "";
            $param_values = $this->params['param_value'] ?? "";

            $len = count($param_ids);
            $paramids = array();
            $k = 0;

            while ($k < $len) {
                $get_param_id = $param_ids[$k];
                $a = array(
                    'uniacid'      => $this->uniacid,
                    'title'        => $param_titles[$k],
                    'value'        => $param_values[$k],
                    'displayorder' => $k,
                    'goodsid'      => $id
                );
                if (!is_numeric($get_param_id)) {
                    $param_id = GoodsParamServiceFacade::insertInfo($a);
                } else {
                    GoodsParamServiceFacade::updateInfo($a, ['id' => $get_param_id]);
                    $param_id = $get_param_id;
                }
                $paramids[] = $param_id;
                ++$k;
            }

            if (0 < count($paramids)) {
                GoodsParamServiceFacade::deleteInfo(['goodsid' => $id, 'id' => Db::raw('not in (' . implode(',', $paramids) . ')')]);
            } else {
                GoodsParamServiceFacade::deleteInfo(['goodsid' => $id]);
            }
            // 参数 end

            show_json(1, array("url" => webUrl("web.goods.index/edit", array("id" => $id, "tab" => str_replace("#tab_", "", $this->params["tab"])))));
        }

        $item = GoodsServiceFacade::getInfo(['id' => $id]);

        $cates = [];
        if (!empty($item["cates"])) {
            $cates = explode(",", $item["cates"]);
        }

        $picList = [];
        if (!empty($item["thumb"])) {
            // $picList = array_merge(array($item["thumb"]), iunserializer($item["thumb_url"]));
            $picList = iunserializer($item["thumb_url"]);
        }

        $thumbOriginal = [];
        if (!empty($item["thumb_original"])) {
            $thumbOriginal = iunserializer($item["thumb_original"]);
        }

        $categorys = GoodsCategoryServiceFacade::getFullCategory(['deleted' => 0, 'uniacid' => $this->uniacid], true);
        $category = array();
        foreach ($categorys as $cate) {
            $category[$cate["id"]] = $cate;
        }

        $levels = [];
        $levels = array_merge(array(array("id" => 0, "key" => "default", "levelname" => (empty($_W["shopset"]["shop"]["levelname"]) ? "默认会员" : $_W["shopset"]["shop"]["levelname"]))), $levels);

        $params = GoodsParamServiceFacade::getAll(['goodsid' => $id], "*", "displayorder asc");

        $result = [
            'category'      => $category,
            'item'          => $item,
            'params'        => $params,
            'picList'       => $picList,
            'thumbOriginal' => $thumbOriginal,
            'cates'         => $cates,
            'levels'        => $levels,
        ];
        return $this->template('post', $result);
    }

    // 获取图片宽高信息
    private function getMediaSize($thumb)
    {
        $thumbPath = $this->iaRoot . "/public/attachment/" . $thumb;
        if (is_file($thumbPath)) {
            $image = Image::open($thumbPath);
            $width = $image->width();
            $height = $image->height();

            return [
                'width'  => $width,
                'height' => $height,
            ];
        }

        return [];
    }

    // 引入模板
    public function tpl()
    {
        $tpl = trim($this->params["tpl"]);
        $template = "";
        if ($tpl == "param") {
            $tag = RandomUtil::random(32);
            $template = $this->template('web/goods/index/tpl/param', ['tag' => $tag]);
        } else {
            $numbers = StringUtil::getUpperNumber();
            if ($tpl == "chapter") {
                $chapter = array(
                    "id"           => RandomUtil::random(32),
                    "displayorder" => intval($this->params["num"]),
                    "title"        => $this->params["title"],
                    "items"        => []
                );
                // dump($chapter);
                // die;
                $template = $this->template('web/goods/index/tpl/chapter', [
                    'numbers' => $numbers,
                    'chapter' => $chapter,
                ]);
            } else {
                if ($tpl == "chapter_item") {
                    $id = $this->params['goodsid'];
                    $chapter = array(
                        "id" => $this->params["chapterid"],
                    );
                    $chapterItem = array(
                        "id"           => RandomUtil::random(32),
                        "title"        => $this->params["title"],
                        "displayorder" => intval($this->params["num"]),
                        "show"         => 1,
                    );
                    $template = $this->template('web/goods/index/tpl/chapter_item', [
                        'numbers'     => $numbers,
                        'id'          => $id,
                        'chapter'     => $chapter,
                        'chapterItem' => $chapterItem,
                    ]);
                }
            }
        }

        return $template;
    }

}
